﻿using Landpy.CruiseControlNet.FacadeInterface.ConfigurationModule;
using Landpy.CruiseControlNet.FacadeInterface.SerializerModule;
using Landpy.CruiseControlNet.Infrastructure.Aop.WrapAttribute;
using System.IO;
using System.Text;
using System;

namespace Landpy.CruiseControlNet.DomainLayer.ConfigurationModule
{
    public class Configuration : IConfiguration
    {
        private ISerializer<CruiseControl> Serializer { get; set; }
        public CruiseControl CruiseControl { get; private set; }

        public Configuration(ISerializer<CruiseControl> serializer)
        {
            this.Serializer = serializer;
        }

        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public CruiseControl Load(string filePath)
        {
            this.CruiseControl = this.Serializer.DeSerializeFile(filePath);
            return this.CruiseControl;
        }

        [NotThrowException]
        [ExceptionMessageBox]
        [LogException]
        public void Save(string filePath, CruiseControl cruiseControl)
        {
            if (File.Exists(filePath))
            {
                File.Copy(filePath, String.Format(@"{0}\{1}{2}.bak", Path.GetDirectoryName(filePath), DateTime.Now.ToString(@"yyyyMMddHHmmss"), Path.GetFileNameWithoutExtension(filePath)));
            }
            string serializedString = this.Serializer.Serialize(cruiseControl);
            using (TextWriter textWriter = new StreamWriter(filePath, false, Encoding.Unicode))
            {
                textWriter.Write(serializedString);
            }
        }
    }
}
